﻿using Nectar.DAL.Common;
using P2PWeb.Common;
using P2PWeb.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;

namespace P2PWeb.Controllers
{
    public class MyBorrowsSearchInfo
    {
        public int PageIndex { get; set; }

        public int[] BorrowStateValues { get; set; }

        public static MyBorrowsSearchInfo Default = new MyBorrowsSearchInfo()
        {
            PageIndex = 1,
        };
    }

    [AccountAuthorize(AccountType.Admin, AccountType.LookThrough, AccountType.User, AccountType.Agent)]
    public class MyBorrowsController : BaseController
    {
        //
        // GET: /MyBorrows/
        public ActionResult Index(MyBorrowsSearchInfo info)
        {
            if (info == null || info.PageIndex==0)
                info = MyBorrowsSearchInfo.Default;
            using (var context = new Repository<P2PModelContainer>())
            {
                Pager<Campaign> pager = new Pager<Campaign>();
                pager.CurrentPageIndex = info.PageIndex;
                QueryParameter isDelParameter = new QueryParameter("isDel", false);
                QueryParameter[] pageParameters = pager.GetQueryParameters();
                int[] borrowStateValuesParameters = (info.BorrowStateValues == null || info.BorrowStateValues.Contains(-1)) ? (int[])Enum.GetValues(typeof(CampaignState)) : info.BorrowStateValues;
                pager.Items = context.GetListOf<Campaign>(" o.Status in {" + string.Format("{0}", string.Join(",", borrowStateValuesParameters)) + "} and o.IsDel=@isDel order by o.CreationTime desc Skip @Skip Limit @Limit",
                    pageParameters.Union(new[] { isDelParameter }).ToArray(),
                   new List<string>(new[] { "CampUpLoad" }));
                pager.TotialItemsCount = context.GetListOf<Campaign>(" o.Status in {" + string.Format("{0}", string.Join(",", borrowStateValuesParameters)) + "} and o.IsDel=@isDel", new[] { isDelParameter }).Count;
                var aa = pager.TotialPaqgerCount;
                ViewData["borrowStateValues"] = info.BorrowStateValues == null ? new[] { -1 } : info.BorrowStateValues;
                ViewData["curAccount"] = CurrentUserInfo;
                if (Request.IsAjaxRequest())
                {
                    return PartialView("MyBorrowsAjax", pager);
                }
                return View(pager);
            }
        }
    }
}
